package dao
import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"config"
	"dao/sql"
	"fmt"
)

//初始化数据库操作对象
//func init()  {
//	db,_ = sql.Open(config.DatabaseType, config.Databasename)
//	db.SetMaxOpenConns(2000)
//	db.SetMaxIdleConns(1000)
//	db.Ping()
//}

type YcDB struct {
	Db *sql.DB
}

func NewYcDB() (*YcDB, error) {
	fmt.Println("database:",(&config.Config{}).String("Databasename"))
	db,_ := sql.Open(config.DatabaseType, (&config.Config{}).String("Databasename"))
	db.SetMaxOpenConns(10)//设置最大连接数
	db.SetMaxIdleConns(1)//设置空闲连接数
	err := db.Ping()
	if err != nil {
		return nil,err
	}
	return &YcDB{db},nil
}

/**
将数据库中查询出来的数据封装成一个map slice
 */

func parsedata(tempRows *sql.Rows) ([]map[string]interface{},error) {
	columns,_ := tempRows.Columns()
	// Make a slice for the values
	values := make([]sql.RawBytes, len(columns))
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	Value := make([]map[string]interface{},0,100)
	//Fetch rows
	for tempRows.Next() {
		// get RawBytes from data
		err := tempRows.Scan(scanArgs...)
		if err != nil {
			panic(err.Error()) // proper error handling instead of panic in your app
		}
		// Now do something with the data.
		// Here we just print each column as a string.
		//var value interface{}
		rowValue := make(map[string]interface{})
		for i, col := range values {
			// Here we can check if the value is nil (NULL value)
			//			if col == nil {
			rowValue[columns[i]] = col
			//			} else {
			rowValue[columns[i]] = string(col)
			//			}
			//rowValue[columns[i]] = col
		}
		Value = append(Value,rowValue)
	}
	return Value,nil
}



func (ycdb *YcDB)QueryAvgTime() ([]map[string]interface{},error) {
	var rows *sql.Rows
	var err error
		rows,err = ycdb.Db.Query(sqlstr.AvgTime)
//		stmtOut,err := ycdb.Db.Prepare(sqlstr.AvgTime)
//		defer stmtOut.Close()
		if err != nil {
			panic(err.Error()) // proper error handling instead of panic in your app
		}
//		rows,err = stmtOut.Query(resId)
	//rows,err := ycdb.Db.Query(ycsql.QueryRunningOrder)
	defer rows.Close()
	if err != nil {
		return nil,err
	}
	AvgTime,err := parsedata(rows)
	return AvgTime,err
}
/*
func (ycdb *YcDB)QueryRunningOrder(resId string) ([]map[string]interface{},error) {
	resIdLength := len(resId)
	var rows *sql.Rows
	var err error
	switch resIdLength {
	case 0:
		rows,err = ycdb.Db.Query(sqlstr.AvgTime)
	case 8:
//		stmtOut,err := ycdb.Db.Prepare(ycsql.QueryRunningOrderwithResId)
		stmtOut,err := ycdb.Db.Prepare(sqlstr.AvgTime)
		defer stmtOut.Close()
		if err != nil {
			panic(err.Error()) // proper error handling instead of panic in your app
		}
		rows,err = stmtOut.Query(resId)
	default:
		return nil,errors.New("Illegal resId")
	}
	//rows,err := ycdb.Db.Query(ycsql.QueryRunningOrder)
	defer rows.Close()
	if err != nil {
		return nil,err
	}
	OrderValue,err := parsedata(rows)
	return OrderValue,err
}
*/